<template>
  <div class="quesiton-main" v-show='!loading'>
    <!-- 点击刷新数据 -->
    <div class='quesiton-mask' @click='refreshList'></div>
    <!-- 顶部会议信息和类型切换 -->
    <div class='question-header'>
      <div class='header-title'>{{meetingInfo.meetingName}}</div>
      <van-tabs
        v-model="activeType"
        color='#0080FF'
        title-active-color='#333333'
        title-inactive-color='#666666'
        line-width="24"
        line-height="3"
        :animated='true'
        @change='changeTab'>
        <van-tab title="全部" name="all"></van-tab>
        <van-tab title="未上墙" name="unShow"></van-tab>
        <van-tab title="已上墙" name="show"></van-tab>
      </van-tabs>
      <div class='header-split'></div>
    </div>
    <!-- 提问列表 -->
    <scroll :isEnd='isEnd'
            @pullup='loadMore'
            :isLoading='true'
            :preventDefaultException='{ tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|AUDIO)$/ }'
            :tagException='{ className: /(^|\s)chat-box(\s|$)/ }'
            ref='scrollBox'>
      <div class="cont">
        <div v-if="noData" class="not-data">暂无提问</div>
        <ul v-if='questionList[0]' class='data-list'>
          <li class='data-item' v-for='(qa, index) of questionList' :key='index'>
            <div class='item-avatar' :style='{backgroundImage: `url(${qa.userAvatar})`}'></div>
            <div class='item-content'>
              <div class='content-title'>
                <span class='title-name'>{{qa.userName}}</span>
                <van-switch
                  v-model='qa.status'
                  active-value='DISPLAYING'
                  @change='toggleDisplay(qa, index)'
                />
              </div>
              <div class='content-text'>{{qa.content}}</div>
              <div class='content-time'>
                <span class='time-text'>{{formatTime(qa.createTime)}}</span>
                <span class='time-reply' @click='replyQa(qa, index)'></span>
              </div>
              <ul class='content-reply' v-show='qa.reply && qa.reply[0]'>
                <li class='reply-item'
                    v-for='(reply, index) of qa.reply'
                    :key='"reply" + index'>
                  {{reply.replyUserName}}：{{reply.content}}
                </li>
              </ul>
            </div>
          </li>
        </ul>
      </div>
    </scroll>
    <!-- 操作按钮 -->
    <div class="bottom">
      <div class="btn" @click='addQa'>新增问题</div>
    </div>
    <!-- 添加问题、回复弹框 -->
    <div class='question-dialog' v-if='isShowDialog'>
      <div class='dialog-body'>
        <div class='dialog-close' @click='closeDialog'></div>
        <div class='dialog-title'>{{dialogType === 'add' ? '新增匿名问题' : '添加回复'}}</div>
        <div class='dialog-input'>
          <textarea
            class='input-textarea'
            maxlength='130'
            v-model='content'
            placeholder='说出你想说的...'>
          </textarea>
          <div class='input-count'>{{content.length}}/130</div>
        </div>
        <div class='dialog-btn' @click='startSave'>保存</div>
      </div>
    </div>
  </div>
</template>
<script>
import scroll from '@/components/scroll'
import { Tabs, Tab, Switch } from 'vant'
export default {
  components: {
    scroll,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [Switch.name]: Switch
  },
  data () {
    return {
      loading: true,
      meetingId: this.$route.query.meetingId,
      // 会议信息
      meetingInfo: {
        meetingName: ''
      },
      // 提问列表
      isEnd: true,
      page: 1,
      pageSize: 10,
      updatePage: 1,
      noData: false,
      questionList: [],
      activeType: 'all',
      qaStatus: null, // null为显示全部的消息
      userAvatar: '',
      // 添加提问、回复
      dialogType: 'add',
      currQa: {},
      isShowDialog: false,
      isLoading: false,
      content: '',
      dialogTitle: ''
    }
  },
  methods: {
    startSave () {
      if (!this.content) {
        return this.$toast('请输入内容')
      }
      if (this.dialogType === 'add') {
        this.saveQuestion()
      } else if (this.dialogType === 'reply') {
        this.addReply()
      }
    },
    // 切换提问的上墙状态
    toggleDisplay (qa, index) {
      // 获取需要更新数据的页码
      this.updatePage = parseInt((index + 1) / 10) + 1
      console.log('updatePage: ', this.updatePage)
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/qa/${sessionStorage.getItem('agentId')}/${this.meetingId}/${qa.qaId}/update`
      let params = {
        status: qa.status === 'DISPLAYING' ? 'DISPLAYING' : 'DISPLAYED',
        userId: sessionStorage.getItem('userId')
      }
      this.$get(url, params).then(res => {
        this.$_load.hide()
        this.$toast(res.message)
        if (res.code === 200) {
          setTimeout(() => {
            this.updateQuestionList()
          }, 200)
        }
      })
    },
    // 点击刷新页面，重新获取提问列表
    refreshList () {
      this.questionList = []
      this.page = 1
      this.fetchQuestionList()
    },
    // 切换提问数据上墙类型
    changeTab () {
      switch (this.activeType) {
        case 'all': this.qaStatus = null; break
        case 'unShow': this.qaStatus = 'NOT_DISPLAY'; break
        case 'show': this.qaStatus = 'DISPLAYING'; break
      }
      this.refreshList()
    },
    resetDialog () {
      this.content = ''
      this.currQa = {}
      this.isShowDialog = false
    },
    replyQa (qa, index) {
      this.currQa = qa
      this.dialogType = 'reply'
      this.updatePage = parseInt((index + 1) / 10) + 1
      this.isShowDialog = true
    },
    addQa () {
      this.dialogType = 'add'
      this.isShowDialog = true
    },
    closeDialog () {
      this.resetDialog()
    },
    formatTime (timeStr) {
      if (!timeStr) {
        return ''
      }
      let date = new Date(timeStr.replace(/-/g, '/'))
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ` + timeStr.slice(11)
    },
    // 保存提问
    saveQuestion () {
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/qa/new`
      let params = {
        content: this.content,
        meetingId: this.meetingId,
        userId: sessionStorage.getItem('userId'),
        userName: sessionStorage.getItem('cpUserName'),
        userAvatar: this.userAvatar,
        corpId: sessionStorage.getItem('corpId'),
        agentId: sessionStorage.getItem('agentId')
      }
      this.$posts(url, params).then(res => {
        this.$_load.hide()
        this.$toast(res.message)
        if (res.code === 200) {
          this.resetDialog()
          this.refreshList()
        }
      })
    },
    // 添加回复
    addReply () {
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/qa/${sessionStorage.getItem('agentId')}/reply`
      let params = {
        content: this.content,
        meetingId: this.meetingId,
        qaId: this.currQa.qaId,
        replyUserId: sessionStorage.getItem('userId'),
        replyUserName: sessionStorage.getItem('cpUserName')
      }
      this.$posts(url, params).then(res => {
        this.$_load.hide()
        this.$toast(res.message)
        if (res.code === 200) {
          this.resetDialog()
          setTimeout(() => {
            this.updateQuestionList()
          }, 200)
        }
      })
    },
    // 获取会议信息
    fetchMeetingInfo () {
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/${sessionStorage.getItem('agentId')}/detail/${this.meetingId}/${sessionStorage.getItem('userId')}`
      this.$get(url).then(res => {
        this.$_load.hide()
        if (res.code === 200) {
          let data = res.data
          if (data) {
            this.meetingInfo = data
            // 获取应用logo作为默认头像
            this.userAvatar = data.squareLogoUrl || ''
          }
        } else {
          this.$toast(res.message)
        }
      })
    },
    // 在操作提问数据后，更新对应页码的提问列表数据
    updateQuestionList () {
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/qa/${sessionStorage.getItem('agentId')}/${this.meetingId}/list`
      let params = {
        currentPage: this.updatePage,
        pageSize: this.pageSize,
        userId: sessionStorage.getItem('userId'),
        qaStatus: this.qaStatus
      }
      this.$get(url, params).then(res => {
        this.$_load.hide()
        if (res.code === 200) {
          let data = res.data
          if (data && data.list && data.list.length) {
            let list = data.list
            // 更新该页码对应的提问上墙状态和回复内容
            this.questionList.forEach(qa => {
              let _qa = list.filter(item => item.qaId === qa.qaId)[0]
              if (_qa) {
                qa.status = _qa.status
                qa.reply = _qa.reply
              }
            })
            this.refreshScroll()
          }
        } else {
          this.$toast(res.message)
        }
      })
    },
    // 获取我的提问
    fetchQuestionList () {
      this.loading = false
      this.$_load.show()
      let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/qa/${sessionStorage.getItem('agentId')}/${this.meetingId}/list`
      let params = {
        currentPage: this.page,
        pageSize: this.pageSize,
        userId: sessionStorage.getItem('userId'),
        qaStatus: this.qaStatus
      }
      this.$get(url, params).then(res => {
        this.$_load.hide()
        if (res.code === 200) {
          let data = res.data
          if (data.total > 0) {
            this.noData = false
          } else {
            this.noData = true
            this.questionList = []
          }
          if (data && data.list && data.list.length) {
            let questionList = data.list
            this.questionList = this.questionList.concat(questionList)
            if (this.questionList.length < data.total) {
              this.isEnd = false
              this.page++
            } else {
              this.isEnd = true
            }
            this.refreshScroll()
          } else {
            this.questionList = []
            this.isEnd = true
          }
        } else {
          this.$toast(res.message)
        }
      })
    },
    // 加载更多
    loadMore () {
      this.fetchQuestionList()
    },
    refreshScroll () {
      setTimeout(() => {
        if (this.$refs.scrollBox) {
          this.$refs.scrollBox.refresh()
        }
      }, 0)
    }
  },
  created () {
    // 判断当前的用户是否有权限进入此页面
    let url = `${this.SERVICE_PORTAL}${this.SERVICE_MEETING}/qa/${sessionStorage.getItem('agentId')}/${this.meetingId}/checkUser/${sessionStorage.getItem('userId')}`
    this.$get(url).then(res => {
      if (res.code === 200) {
        if (res.data) {
          this.fetchMeetingInfo()
          this.fetchQuestionList()
        } else {
          window.eventBus.$emit('showVisitLimit', '您无权限访问，请联系管理员')
        }
      } else {
        this.$toast(res.message)
      }
    })
  }
}
</script>
<style lang="stylus" scoped>
.quesiton-main
  width 100%
  height 100vh
  background #fff
  position relative
  display flex
  flex-direction column
  .quesiton-mask
    position fixed
    right 12px
    bottom 96px
    z-index 100
    width: 36px;
    height: 36px;
    box-shadow: 0px 5px 10px 0px rgba(48, 50, 51, 0.2);
    border-radius: 28px;
    background #FFFFFF url('~assets/img/ic_question_refresh@2x.png') no-repeat center / 16px
  .question-header
    flex none
    .header-title
      padding 13px 28px
      font-size: 16px;
      font-weight: 700;
      color: #333333;
      line-height: 22px;
      text-align center
    >>> .van-tab--active
      font-weight 700
    .header-split
      height 9px
      background: #F2F4F5;
  .c_scroll
    position relative
    flex 1
  .cont
    min-height calc(100vh - 151px)
    width 100%
    .not-data
      width calc(100% - 30px)
      height 140px
      margin 0 auto
      line-height 240px
      text-align center
      font-size 14px
      color #B2B2B2
      border-radius 8px
    .data-list
      padding 12px
      .data-item
        display flex
        margin-bottom 12px
        &:last-child
          .item-content
            border-bottom none
        .item-avatar
          flex none
          width 28px
          height 28px
          border-radius 50%
          margin-right 6px
          margin-top 3px
          bgCover()
        .item-content
          flex 1
          padding-bottom 12px
          border-bottom 1px solid #EEEEEE
          .content-title
            display flex
            align-items center
            justify-content space-between
            .title-name
              flex none
              font-size: 14px;
              font-weight: 400;
              color: #666666;
              line-height: 20px;
            .van-switch
              transform scale(0.55)
              transform-origin 100% center
              background #eee
              &.van-switch--on
                background #0080ff
          .content-text
            font-size: 13px;
            font-weight: 400;
            color: #333333;
            line-height: 18px;
            margin 4px 0
          .content-time
            display flex
            align-items center
            justify-content space-between
            .time-text
              font-size: 12px;
              font-weight: 400;
              color: #999999;
              line-height: 17px;
            .time-reply
              width 28px
              height 18px
              background url('~assets/img/ic_question_reply@2x.png') no-repeat center / 18px
          .content-reply
            margin-top 8px
            .reply-item
              background: #F5F7FA;
              border-radius: 4px;
              margin-bottom 8px
              padding 13px 12px
              font-size: 13px;
              font-weight: 400;
              color: #666666;
              line-height: 18px;
  // 底部按钮
  .bottom
    flex none
    width 100%
    height 50px
    background #fff
    box-shadow: 0px -1px 10px 0px rgba(76, 81, 86, 0.1)
    padded_box(border-box, 6px 16px)
    .btn
      width 100%
      height 38px
      background #0080FF
      line-height 18px
      text-align center
      font-size 14px
      color #fff
      padded_box(border-box, 10px 0)
      border-radius 16px
  // 提交问题、回复问题
  .question-dialog
    position absolute
    left 0
    right 0
    top 0
    bottom 0
    z-index 1000
    background: rgba(0, 0, 0, 0.6)
    .dialog-body
      position absolute
      left 50%
      top 50%
      transform translate(-50%, -50%)
      box-sizing border-box
      height 300px
      width calc(100vw - 48px)
      background: #FFFFFF;
      box-shadow: 0px 5px 15px 0px rgba(0, 0, 0, 0.1);
      border-radius: 6px;
      padding 16px 12px
      .dialog-close
        position absolute
        right 16px
        top 16px
        width 20px
        height 20px
        background url('~assets/img/ic_question_close@2x.png') no-repeat 0 0 / 100%
      .dialog-title
        font-size: 16px;
        font-weight: 700;
        color: #333333;
        line-height: 22px;
        margin-bottom 8px
        text-align center
      .dialog-input
        border-radius: 4px;
        border: 1px solid #E6E6E6;
        padding 8px
        .input-textarea
          height 140px
          resize none
          font-size 14px
          line-height 20px
          &::-webkit-input-placeholder
            font-size: 14px;
            font-weight: 400;
            color: #999999;
            line-height: 20px;
        .input-count
          font-size: 12px;
          font-weight: 400;
          color: #999999;
          line-height: 17px;
          text-align right
      .dialog-btn
        height: 38px;
        line-height 38px
        background: #0083FF;
        border-radius: 19px;
        text-align center
        font-size: 14px;
        font-weight: 500;
        color: #FFFFFF;
        letter-spacing 1px
        margin-top 24px
</style>
